﻿using EkStudio.com.bean.xml.BillModule;
using EkStudio.com.bean.xml.RootInterface;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.bean.xml.RootInterface.FieldEvent;
using EkStudio.com.ui.form.Auto;
using EkStudio.Com.UI.Interface;
using ScintillaNET;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace EkStudio.com.ui.form.FieldDropSource
{
    public partial class AutoDropStyle : DevExpress.XtraEditors.XtraForm
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AutoDropStyle));

        private ProjectRootPanel RootPanel = null;

        private ProjectUnitBillInterface UnitPanel = null;

        private string AutoCompleteKeywords = "select from where and";

        private DataTable WhereData = null, OutData = null,FixedData = null;

        private BillFormatModule module = null;

        private List<BillFormatModule> ModList = new List<BillFormatModule>();//引用模块列表

        private List<string> ModPathList = new List<string>();//选取的字段组列表

        private List<OutFieldData> outList = null;

        private BillUiFieldsItem dataFill = null;//事件配置

        private BillUiGroupItems group = null;//字段分组

        private ModuleFieldSelectForm SelectForm = null;


        public AutoDropStyle(ProjectRootPanel root,BillFormatModule bean,ProjectUnitBillInterface unit)
        {
            InitializeComponent();
            this.RootPanel = root;
            this.module = bean;
            this.UnitPanel = unit;
            this.InitForm();
        }

        private void InitForm()
        {
            #region 初始化编辑器
            this.SqlEdit.Margins[0].Width = 20;
            this.SqlEdit.Margins[2].Type = MarginType.Symbol;
            this.SqlEdit.Margins[2].Mask = Marker.MaskFolders;
            this.SqlEdit.Margins[2].Sensitive = true;
            this.SqlEdit.Margins[2].Width = 20;

            SqlEdit.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
            SqlEdit.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
            SqlEdit.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
            SqlEdit.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
            SqlEdit.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
            SqlEdit.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
            SqlEdit.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;

            SqlEdit.StyleResetDefault();
            SqlEdit.Styles[Style.Default].Font = "Consolas";
            SqlEdit.Styles[Style.Default].Size = 10;
            SqlEdit.StyleClearAll();


            // Configure the CPP (C#) lexer styles
            SqlEdit.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
            SqlEdit.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
            SqlEdit.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
            SqlEdit.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
            SqlEdit.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
            SqlEdit.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
            SqlEdit.Lexer = Lexer.Cpp;

            // Set the keywords
            //SqlEdit.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
            //SqlEdit.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

            SqlEdit.SetKeywords(0, common.unit.ULabel.SQLKeys);

            #endregion

            #region 数据配置 

            WhereData = new DataTable();
            WhereData.Columns.Add("key", typeof(string));
            WhereData.Columns.Add("caption", typeof(string));
            WhereData.Columns.Add("column", typeof(string));
            WhereData.Columns.Add("etype", typeof(string));

            GridControl.DataSource = WhereData;

            OutData = new DataTable();

            OutData.Columns.Add("SourceField", typeof(string));//字段
            OutData.Columns.Add("SelfColumn", typeof(bool));//输出当前字段
            OutData.Columns.Add("ColumnValue", typeof(string));//输出字段标签路径
            OutData.Columns.Add("CaptionColumn", typeof(string));//输出字段显示标签
            OutData.Columns.Add("VisibleColumn", typeof(bool));//是否显示
            OutData.Columns.Add("WidthColumn", typeof(int));//宽度
            OutData.Columns.Add("DescType", typeof(string));//排序
            OutData.Columns.Add("SearchType", typeof(bool));//可否查询
            OutData.Columns.Add("column", typeof(string));//输出字段名称
            OutData.Columns.Add("languageTexts", typeof(string));//多语言标签
            OutData.Columns.Add("SelfTempValue",typeof(string));//临时字段
            OutData.Columns.Add("Trigger", typeof(bool));//触发事件
            OutGridControl.DataSource = OutData;


            FixedData = new DataTable("TableName");
            FixedData.Columns.Add("Key", typeof(string));
            FixedData.Columns.Add("Value", typeof(string));
            GridFixedTab.DataSource = FixedData;

            this.SqlWhereGrid.OptionsBehavior.Editable = !UnitPanel.ReadOnly;
            this.GridFixedView.OptionsBehavior.Editable = !UnitPanel.ReadOnly;
            this.OutGridView.OptionsBehavior.Editable = !UnitPanel.ReadOnly;
            this.RadioGroupList.ReadOnly = UnitPanel.ReadOnly;

            this.SubmitBtn.Enabled = !UnitPanel.ReadOnly;
            
            #endregion
        }

        private void InitParam()
        {
            #region 处理输出列表
            RepositoryOutFieldList.Items.Clear();
            string sql = SqlEdit.Text;
            if (sql.Length > 0)
            {
                sql = removeBracket(sql).ToLower();
                int index = sql.IndexOf("from");
                if (index != -1)
                {
                    sql = sql.Substring(0, index).Replace("select", "").Replace("\n", " ");
                    string[] keyList = sql.Split(',');
                    if (keyList.Length > 0)
                    {
                        for (int i = 0; i < keyList.Length; i++)
                        {
                            StringBuilder value = new StringBuilder();
                            string key = keyList[i].Trim();
                            int len = key.Length;
                            char ch = key[len - 1];
                            while (ch != ' ' && ch != '.' && len > 0)
                            {
                                value.Insert(0, ch);
                                len--;
                                if (len > 0) ch = key[len - 1];
                            }
                            RepositoryOutFieldList.Items.Add(value.ToString());
                        }
                    }
                }
            }
            #endregion
            #region 处理条件参数
            RepositoryParamList.Items.Clear();
            sql = SqlEdit.Text;
            int ind = sql.IndexOf(":");
            while (ind > 0)
            {
                int begin = ind;
                int end = -1;
                StringBuilder value = new StringBuilder();
                for (int i = begin + 1; i < sql.Length; i++)
                {
                    if (sql[i] == ' ' || sql[i] == '\n' || sql[i] == ')' || sql[i] == '(' || sql[i] == '\t')//非字母
                    {
                        end = i;
                        break;
                    }
                }
                if (end == -1)
                {
                    string str = sql.Substring(begin + 1).Trim();
                    RepositoryParamList.Items.Add(str);
                    value.Append(sql.Substring(0, begin)).Append(" ");
                }
                else
                {
                    //"sssdsdfsdfsdfsdf"
                    int width = end - begin - 1;
                    string str = sql.Substring(begin + 1, width);
                    logger.Info(string.Format("开始位置{0},结束位置[{1}],长度{2},字符[{3},取值[{4}]]", begin + 1, end, width, sql, str));

                    RepositoryParamList.Items.Add(str);
                    value.Append(sql.Substring(0, begin)).Append(" ");
                    value.Append(sql.Substring(end + 1));
                }
                sql = value.ToString();
                ind = sql.IndexOf(":");
            }
            #endregion
        }

        /// <summary>
        /// 设置显示字段
        /// </summary>
        /// <param name="field"></param>
        public void SetSelectField(BillUiFieldsItem field,BillUiGroupItems group)
        {
            WhereData.Rows.Clear();
            OutData.Rows.Clear();
            FixedData.Rows.Clear();

            ModList.Clear();
            ModPathList.Clear();

            this.SqlEdit.Text = "";

            this.dataFill = field;
            this.group = group;

            if (field.EditProperty.DropListStyle == null)
            {
                field.EditProperty.DropListStyle = new BillUiFieldsDropListStyle();
            }
            BillUiFieldsDropListStyle style = field.EditProperty.DropListStyle;
            RadioGroupList.SelectedIndex = style.Type;
            if(style.Type == 1) //固定
            {
                if (style.DefaultList != null&&style.DefaultList.Count>0)
                {
                    foreach(BillUiFieldsDropListDefault val in style.DefaultList)
                    {
                        DataRow Row = FixedData.NewRow();
                        Row["Key"] = val.Key;
                        Row["Value"] = val.Value;
                        FixedData.Rows.Add(Row);
                    }
                }
            }else if(style.Type == 2)//数据源
            {
                if (style.SqlText != null)
                {
                    this.SqlEdit.Text = style.SqlText.Content;
                }
                //条件
                if (style.SqlWhere != null&&style.SqlWhere.WhereItems!=null&&style.SqlWhere.WhereItems.Count>0)
                {
                    foreach (BillDataFillsqlWhereItem wIt in style.SqlWhere.WhereItems)
                    {
                        DataRow Row = WhereData.NewRow();
                        Row["key"] = wIt.Key;
                        Row["caption"] = wIt.Caption;
                        Row["column"] = wIt.Column;
                        Row["etype"] = wIt.Etype;
                        WhereData.Rows.Add(Row);
                    }
                }
                //输出
                if(style.SqlValue!=null && style.SqlValue.ValueItem != null && style.SqlValue.ValueItem.Count > 0)
                {
                    foreach (BillDataFillSqlValueItem vIt in style.SqlValue.ValueItem)
                    {
                        DataRow row = OutData.NewRow();
                        row["SourceField"] = vIt.Key;
                        row["SelfColumn"] = vIt.Column == "value";
                        row["SelfTempValue"] = "";
                        row["ColumnValue"] = vIt.Caption;
                        row["CaptionColumn"] = vIt.ShowCaption;
                        row["VisibleColumn"] = vIt.Visible;
                        row["WidthColumn"] = vIt.Width;
                        row["DescType"] = vIt.Order;
                        row["SearchType"] = vIt.Search;
                        row["column"] = vIt.Column;
                        row["languageTexts"] = vIt.LanguageTexts;
                        row["Trigger"] = vIt.Trigger;
                        OutData.Rows.Add(row);
                    }
                }
            }
            else //无数据
            {

            }
            this.GridFixedTab.Refresh();
            this.GridControl.Refresh();
            this.OutGridControl.Refresh();


        }

        private void SqlEdit_CharAdded(object sender, CharAddedEventArgs e)
        {
            // Find the word start
            var currentPos = SqlEdit.CurrentPosition;
            var wordStartPos = SqlEdit.WordStartPosition(currentPos, true);
            // Display the autocompletion list
            var lenEntered = currentPos - wordStartPos;
            if (lenEntered > 0)
            {
                SqlEdit.AutoCShow(lenEntered, AutoCompleteKeywords);
            }
        }


        private void SqlTabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (SqlEdit.Text.Trim() != "")
            {
                InitParam();
            } 
        }
        /// <summary>
        /// 输出表格内容改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutGridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int RIndex = e.RowHandle;
            if (e.Column.Name == "OutCaptionColumn")
            {
                string val = e.Value.ToString();
                if (val != "" && this.outList != null)
                {
                    bool look = false;
                    foreach (OutFieldData data in this.outList)
                    {
                        if (data.ShortCaption == val)
                        {
                            OutData.Rows[e.RowHandle]["languageTexts"] = data.LanguageText;
                            look = true;
                            break;
                        }
                    }
                    if (!look) OutData.Rows[e.RowHandle]["languageTexts"] = "";
                }
                else
                {
                    OutData.Rows[e.RowHandle]["languageTexts"] = "";
                }
            }
            else if (e.Column.FieldName == "SelfColumn")
            {
                DataRow Row = OutData.Rows[RIndex];
                if (e.Value.Equals(true))
                {
                    Row["SelfTempValue"] = Row["column"];
                    Row["column"] = "value";
                    int i = 0;
                    foreach (DataRow tRow in OutData.Rows)
                    {
                        if (i != RIndex)
                        {
                            tRow["SelfColumn"] = false;
                        }
                        i++;
                    }
                    OutGridView.RefreshData();
                }
                else
                {
                    Row["column"] = Row["SelfTempValue"];

                }
            }
        }


        private void AutoSqlBtn_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            AutoQueryFormula AutoQForm = new AutoQueryFormula(module, RootPanel);
            DialogResult DR = AutoQForm.ShowDialog();
            if (DR == DialogResult.OK)
            {
                //sql语句
                SqlEdit.Text = AutoQForm.SqlContent;
                //条件
                DataTable DataList = AutoQForm.ReqData;
                if (DataList.Rows.Count > 0)
                {
                    WhereData.Rows.Clear();
                    foreach (DataRow Row in DataList.Rows)
                    {
                        //WhereData.Columns.Add("key", typeof(string));
                        //WhereData.Columns.Add("caption", typeof(string));
                        //WhereData.Columns.Add("column", typeof(string));
                        DataRow whRow = WhereData.NewRow();
                        whRow["key"] = Row["FieldParamKey"];
                        whRow["caption"] = Row["FieldReqCaption"];
                        whRow["column"] = Row["FieldReqValue"];
                        whRow["etype"] = "=";
                        WhereData.Rows.Add(whRow);
                    }
                    SqlWhereGrid.RefreshData();
                }
                //输出
                outList = AutoQForm.OutList;
                RepositoryLanguageList.Items.Clear();
                if (outList.Count > 0)
                {
                    foreach (OutFieldData data in outList)
                    {
                        if (data.ShortCaption != "")
                            RepositoryLanguageList.Items.Add(data.ShortCaption);
                    }
                }

                //输出字段
                //RepositoryOutFieldList
                OutData.Rows.Clear();
                DataTable outTable = AutoQForm.OutData;
                if (outTable.Rows.Count > 0)
                {
                    foreach (DataRow data in outTable.Rows)
                    {
                        DataRow Row = OutData.NewRow();
                        
                        
                        if (data["ColFieldName"] is OutFieldData)
                        {
                            OutFieldData field = (OutFieldData)data["ColFieldName"];
                            Row["SourceField"] = field.Key;
                            Row["CaptionColumn"] = field.ShortCaption;
                            Row["languageTexts"] = field.LanguageText;
                        }
                        else
                        {
                            Row["SourceField"] = "";
                            Row["CaptionColumn"] = "";
                            Row["languageTexts"] = "";
                        }
                        if(data["ColWriteField"] is OutFieldData)
                        {
                            OutFieldData outField = (OutFieldData)data["ColWriteField"];
                            Row["ColumnValue"] = outField.Caption;
                            Row["column"] = outField.Key;
                        }
                        else
                        {
                            Row["ColumnValue"] = "";
                            Row["column"] = "";
                        }

                        Row["SelfColumn"] = false;
                        Row["SelfTempValue"] = "";
                        Row["VisibleColumn"] = data["ColVisible"];
                        Row["WidthColumn"] = data["ColFieldWidth"];
                        Row["DescType"] = "";
                        Row["SearchType"] = data["ColShowSearch"];
                        Row["Trigger"] = true;
                        
                        OutData.Rows.Add(Row);
                    }
                }
                OutGridView.RefreshData();
            }

        }


        /// <summary>
        /// 添加记录行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddRow_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (RadioGroupList.SelectedIndex == 1)
            {
                DataRow row = FixedData.NewRow();
                row["Key"] = "";
                row["Value"] = "";
                FixedData.Rows.Add(row);
                this.GridFixedView.RefreshData();
                this.GridFixedView.MoveLast();
            }
            else if(RadioGroupList.SelectedIndex == 2)
            {
                if (SqlTabControl.SelectedTabPage.Name == "WhereTabPage")
                {
                    DataRow row = WhereData.NewRow();
                    row["key"] = "";
                    row["caption"] = "";
                    row["column"] = "";
                    row["etype"] = "=";
                    WhereData.Rows.Add(row);
                    SqlWhereGrid.RefreshData();
                    SqlWhereGrid.MoveLast();
                }
                else if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
                {
                    DataRow row = OutData.NewRow();
                    row["SourceField"] = "";
                    row["SelfColumn"] = false;
                    row["SelfTempValue"] = "";
                    row["ColumnValue"] = "";
                    row["CaptionColumn"] = "";
                    row["VisibleColumn"] = true;
                    row["WidthColumn"] = 100;
                    row["DescType"] = "";
                    row["SearchType"] = true;
                    row["column"] = "";
                    row["languageTexts"] = "";
                    row["Trigger"] = true;
                    OutData.Rows.Add(row);
                    OutGridView.RefreshData();
                    OutGridView.MoveLast();
                }
            }

            
        }

        /// <summary>
        /// 删除记录行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteRow_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (RadioGroupList.SelectedIndex == 1)
            {
                this.GridFixedView.DeleteSelectedRows();
                this.GridFixedView.MoveLast();
            }
            else if(RadioGroupList.SelectedIndex == 2)
            {
                if (SqlTabControl.SelectedTabPage.Name == "WhereTabPage")
                {
                    SqlWhereGrid.DeleteSelectedRows();
                    SqlWhereGrid.MoveLast();
                }
                else if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
                {
                    OutGridView.DeleteSelectedRows();
                    OutGridView.MoveLast();
                }
            }
        }

        /// <summary>
        /// 记录上移
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MoveUp_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (RadioGroupList.SelectedIndex == 1)
            {
                int RHandleIndex = GridFixedView.FocusedRowHandle;
                if (RHandleIndex > 0)
                {
                    //保存当前记录
                    DataRow row = FixedData.Rows[RHandleIndex];
                    string key = (string)row["Key"];
                    string column = (string)row["Value"];

                    //修改当前行为上一行记录
                    DataRow PevRow = FixedData.Rows[RHandleIndex - 1];
                    row["Key"] = PevRow["Key"];
                    row["Value"] = PevRow["Value"];

                    //修改上一行为当前行记录
                    PevRow["Key"] = key;
                    PevRow["Value"] = column;

                    GridFixedView.RefreshRow(RHandleIndex - 1);
                    GridFixedView.RefreshRow(RHandleIndex);
                    //选中上一行
                    GridFixedView.MovePrev();
                }
            }
             else if (RadioGroupList.SelectedIndex == 2)
            {
                if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
                {
                    int CHandleIndex = OutGridView.FocusedRowHandle;
                    if (CHandleIndex > 0)
                    {
                        DataRow row = OutData.Rows[CHandleIndex];
                        //保存当前行记录
                        BillDataFillSqlValueItem it = new BillDataFillSqlValueItem();
                        it.Key = (string)row["SourceField"];
                        it.Caption = (string)row["ColumnValue"];
                        it.Column = (string)row["column"];
                        it.ShowCaption = (string)row["CaptionColumn"];
                        it.Visible = (bool)row["VisibleColumn"];
                        it.Width = (int)row["WidthColumn"];
                        it.Order = (string)row["DescType"];
                        it.Search = (bool)row["SearchType"];
                        it.LanguageTexts = (string)row["languageTexts"];
                        string SelfTempValue = (string)row["SelfTempValue"];

                       

                        //修改当前行为上一行记录
                        DataRow PevRow = OutData.Rows[CHandleIndex - 1];
                        row["SourceField"] = PevRow["SourceField"];
                        row["SelfColumn"] = PevRow["SelfColumn"];
                        row["SelfTempValue"] = PevRow["SelfTempValue"];
                        row["ColumnValue"] = PevRow["ColumnValue"];
                        row["CaptionColumn"] = PevRow["CaptionColumn"];
                        row["VisibleColumn"] = PevRow["VisibleColumn"];
                        row["WidthColumn"] = PevRow["WidthColumn"];
                        row["DescType"] = PevRow["DescType"];
                        row["SearchType"] = PevRow["SearchType"];
                        row["column"] = PevRow["column"];
                        row["languageTexts"] = PevRow["languageTexts"];

                        //修改上一行为当前行记录
                        PevRow["SourceField"] = it.Key;
                        PevRow["SelfColumn"] = it.Column == "value";
                        PevRow["SelfTempValue"] = SelfTempValue;
                        PevRow["ColumnValue"] = it.Caption;
                        PevRow["CaptionColumn"] = it.ShowCaption;
                        PevRow["VisibleColumn"] = it.Visible;
                        PevRow["WidthColumn"] = it.Width;
                        PevRow["DescType"] = it.Order;
                        PevRow["SearchType"] = it.Search;
                        PevRow["column"] = it.Column;
                        PevRow["languageTexts"] = it.LanguageTexts;




                        OutGridView.RefreshRow(CHandleIndex - 1);
                        OutGridView.RefreshRow(CHandleIndex);
                        //选中上一行
                        OutGridView.MovePrev();
                    }
                }
            }
            
        }

        private void MoveDown_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (RadioGroupList.SelectedIndex == 1)
            {
                int RHandleIndex = GridFixedView.FocusedRowHandle;
                if (RHandleIndex >= 0 && RHandleIndex < GridFixedView.RowCount - 1)
                {
                    //保存当前记录
                    DataRow row = FixedData.Rows[RHandleIndex];
                    string key = (string)row["Key"];
                    string caption = (string)row["Value"];

                    //修改当前行为下一行记录
                    DataRow PevRow = FixedData.Rows[RHandleIndex + 1];
                    row["Key"] = PevRow["Key"];
                    row["Value"] = PevRow["Value"];

                    //修改下一行为当前行记录
                    PevRow["Key"] = key;
                    PevRow["Value"] = caption;

                    GridFixedView.RefreshRow(RHandleIndex);
                    GridFixedView.RefreshRow(RHandleIndex + 1);
                    //选中上一行
                    GridFixedView.MoveNext();
                }
            }
            else if (RadioGroupList.SelectedIndex == 2)
            {
                if (SqlTabControl.SelectedTabPage.Name == "ValueTabPage")
                {
                    int CHandleIndex = OutGridView.FocusedRowHandle;
                    if (CHandleIndex >= 0 && CHandleIndex < OutGridView.RowCount - 1)
                    {
                        DataRow row = OutData.Rows[CHandleIndex];
                        //保存当前行记录
                        BillDataFillSqlValueItem it = new BillDataFillSqlValueItem();
                        it.Key = (string)row["SourceField"];
                        it.Caption = (string)row["ColumnValue"];
                        it.Column = (string)row["column"];
                        it.ShowCaption = (string)row["CaptionColumn"];
                        it.Visible = (bool)row["VisibleColumn"];
                        it.Width = (int)row["WidthColumn"];
                        it.Order = (string)row["DescType"];
                        it.Search = (bool)row["SearchType"];
                        it.LanguageTexts = (string)row["languageTexts"];
                        string SelfTempValue = (string)row["SelfTempValue"];

                        //修改当前行为下一行记录
                        DataRow PevRow = OutData.Rows[CHandleIndex + 1];
                        row["SourceField"] = PevRow["SourceField"];
                        row["SelfColumn"] = PevRow["SelfColumn"];
                        row["SelfTempValue"] = PevRow["SelfTempValue"];
                        row["ColumnValue"] = PevRow["ColumnValue"];
                        row["CaptionColumn"] = PevRow["CaptionColumn"];
                        row["VisibleColumn"] = PevRow["VisibleColumn"];
                        row["WidthColumn"] = PevRow["WidthColumn"];
                        row["DescType"] = PevRow["DescType"];
                        row["SearchType"] = PevRow["SearchType"];
                        row["column"] = PevRow["column"];
                        row["languageTexts"] = PevRow["languageTexts"];

                        //修改下一行为当前行记录
                        PevRow["SourceField"] = it.Key;
                        PevRow["SelfColumn"] = it.Column == "value";
                        PevRow["SelfTempValue"] = SelfTempValue;
                        PevRow["ColumnValue"] = it.Caption;
                        PevRow["CaptionColumn"] = it.ShowCaption;
                        PevRow["VisibleColumn"] = it.Visible;
                        PevRow["WidthColumn"] = it.Width;
                        PevRow["DescType"] = it.Order;
                        PevRow["SearchType"] = it.Search;
                        PevRow["column"] = it.Column;
                        PevRow["languageTexts"] = it.LanguageTexts;

                        OutGridView.RefreshRow(CHandleIndex);
                        OutGridView.RefreshRow(CHandleIndex + 1);
                        //选中下一行
                        OutGridView.MoveNext();
                    }
                }
            }
            
        }




        #region 窗口移动

        private bool isMouseDown = false;
        private Point FormLocation;     //form的location
        private Point mouseOffset;      //鼠标的按下位置

        private void ModuleFieldSelectForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                FormLocation = this.Location;
                mouseOffset = Control.MousePosition;
            }
        }

        private void ModuleFieldSelectForm_MouseMove(object sender, MouseEventArgs e)
        {
            int _x = 0;
            int _y = 0;
            if (isMouseDown)
            {
                Point pt = Control.MousePosition;
                _x = mouseOffset.X - pt.X;
                _y = mouseOffset.Y - pt.Y;

                this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y);
            }
        }

        private void ModuleFieldSelectForm_MouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
        }

        #endregion



        private void RadioGroupList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            CardPanel.SelectedTabPageIndex = RadioGroupList.SelectedIndex;
            if(RadioGroupList.SelectedIndex == 2 || RadioGroupList.SelectedIndex ==1)
            {
                AutoSqlBtn.Enabled = true;
                MoveUp.Enabled = true;
                MoveDown.Enabled = true;
                AddRow.Enabled = true;
                DeleteRow.Enabled = true;
            }
            else
            {
                AutoSqlBtn.Enabled = false;
                MoveUp.Enabled = false;
                MoveDown.Enabled = false;
                AddRow.Enabled = false;
                DeleteRow.Enabled = false;
            }
        }
        /// <summary>
        /// 固定值修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridFixedView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int RHandlerIndex = e.RowHandle;
            if (RHandlerIndex >= 0)
            {
                DataRow Row = FixedData.Rows[RHandlerIndex];
                Row["Value"] = Row["Key"];
                GridFixedView.RefreshRow(RHandlerIndex);
            }
        }
        /// <summary>
        /// 输出确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SubmitBtn_Click(object sender, System.EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (dataFill.EditProperty.DropListStyle == null)
            {
                dataFill.EditProperty.DropListStyle = new BillUiFieldsDropListStyle();
            }
            if (RadioGroupList.SelectedIndex == 0)
            {
                dataFill.EditProperty.DropListStyle.Type = 0;
                dataFill.EditProperty.DropListStyle.DefaultList = null;
                dataFill.EditProperty.DropListStyle.SqlText = null;
                dataFill.EditProperty.DropListStyle.SqlWhere = null;
                dataFill.EditProperty.DropListStyle.SqlValue = null;
            }else if(RadioGroupList.SelectedIndex == 1)
            {
                dataFill.EditProperty.DropListStyle.Type = 1;
                dataFill.EditProperty.DropListStyle.DefaultList = new List<BillUiFieldsDropListDefault>();
                dataFill.EditProperty.DropListStyle.SqlText = null;
                dataFill.EditProperty.DropListStyle.SqlWhere = null;
                dataFill.EditProperty.DropListStyle.SqlValue = null;

                if (FixedData.Rows.Count > 0)
                {
                    foreach(DataRow Row in FixedData.Rows)
                    {
                        BillUiFieldsDropListDefault it = new BillUiFieldsDropListDefault();
                        it.Key = (string)Row["Key"];
                        it.Value = (string)Row["Value"];
                        dataFill.EditProperty.DropListStyle.DefaultList.Add(it);
                    }
                }
            }else if(RadioGroupList.SelectedIndex == 2)
            {
                dataFill.EditProperty.DropListStyle.Type = 2;
                dataFill.EditProperty.DropListStyle.DefaultList = null;
                dataFill.EditProperty.DropListStyle.SqlText = new BillDataFillsqlSource();
               

                dataFill.EditProperty.DropListStyle.SqlText.Content = this.SqlEdit.Text;

                dataFill.EditProperty.DropListStyle.SqlWhere = new BillDataFillsqlWhere();
                if (this.WhereData.Rows.Count > 0)
                {
                    dataFill.EditProperty.DropListStyle.SqlWhere.WhereItems = new List<BillDataFillsqlWhereItem>();
                    foreach (DataRow Row in this.WhereData.Rows)
                    {
                        BillDataFillsqlWhereItem it = new BillDataFillsqlWhereItem();
                        it.Key = (string)Row["key"];
                        it.Caption = (string)Row["caption"];
                        it.Column = (string)Row["column"];
                        it.Etype = (string)Row["etype"];
                        dataFill.EditProperty.DropListStyle.SqlWhere.WhereItems.Add(it);
                    }
                }
                dataFill.EditProperty.DropListStyle.SqlValue = new BillDataFillSqlValue();
                if (this.OutData.Rows.Count > 0)
                {
                    dataFill.EditProperty.DropListStyle.SqlValue.ValueItem = new List<BillDataFillSqlValueItem>();
                    foreach(DataRow Row in this.OutData.Rows)
                    {
                        BillDataFillSqlValueItem it = new BillDataFillSqlValueItem();

                        it.Key = (string)Row["SourceField"];
                        it.Column = (string)Row["column"];
                        it.Caption = (string)Row["ColumnValue"];
                        it.ShowCaption = (string)Row["CaptionColumn"];
                        it.Visible = (bool)Row["VisibleColumn"];
                        it.Width = System.Convert.ToInt32(Row["WidthColumn"]);
                        it.LanguageTexts = System.Convert.ToString(Row["languageTexts"]);
                        it.Search = System.Convert.ToBoolean(Row["SearchType"]);
                        it.Order = System.Convert.ToString(Row["DescType"]);
                        it.Trigger = System.Convert.ToBoolean(Row["Trigger"]);
                        dataFill.EditProperty.DropListStyle.SqlValue.ValueItem.Add(it);
                    }
                }
            }

            this.UnitPanel.SaveStatus = false;
        }
        /// <summary>
        /// 取值条件当前界面取值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryParamValue_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int[] SRows = SqlWhereGrid.GetSelectedRows();
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                if (SRows.Length > 0)
                {
                    int RowHandle = SRows[0];
                    if (SelectForm == null) SelectForm = new ModuleFieldSelectForm();
                    SelectForm.SetFormatBill(module);
                    DialogResult DR = SelectForm.ShowDialog();
                    if (DR == DialogResult.OK)
                    {
                        BillUiFieldsItem field = SelectForm.SelectField;
                        if (field != null)
                        {
                            //WhereData = new DataTable();
                            //WhereData.Columns.Add("key", typeof(string));
                            //WhereData.Columns.Add("caption", typeof(string));
                            //WhereData.Columns.Add("column", typeof(string));
                            DataRow row = WhereData.Rows[RowHandle];
                            row["caption"] = SelectForm.SelectPaths.Count > 0 ? SelectForm.SelectPaths[0] : "";
                            row["column"] = field.Key;

                        }
                    }
                    SqlWhereGrid.RefreshRow(RowHandle);
                }
            }
            else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                if (SRows.Length > 0)
                {
                    int RowHandle = SRows[0];
                    DataRow row = WhereData.Rows[RowHandle];
                    row["caption"] = "";
                    row["column"] = "";
                    SqlWhereGrid.RefreshRow(RowHandle);
                }
            }
        }
        /// <summary>
        /// 输出字段选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepositoryOutSelectField_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //选择输出字段
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                int[] row = OutGridView.GetSelectedRows();
                if (row.Length > 0)
                {
                    int RowHandle = row[0];
                    if (SelectForm == null) SelectForm = new ModuleFieldSelectForm();
                    if (this.group!=null&&this.group.Table)
                    {
                        SelectForm.SetFormatBill(module, this.group.Key);
                    }
                    else
                    {
                        SelectForm.SetFormatBill(module);
                    }

                    DialogResult DR = SelectForm.ShowDialog();
                    if (DR == DialogResult.OK)
                    {
                        BillUiFieldsItem field = SelectForm.SelectField;
                        if (field != null)
                        {
                            DataRow data = OutData.Rows[RowHandle];
                            data["ColumnValue"] = SelectForm.SelectPaths.Count > 0 ? SelectForm.SelectPaths[0] : "";
                            data["CaptionColumn"] = field.Caption;
                            data["column"] = field.Key;
                            data["languageTexts"] = field.LanguageTexts;
                        }
                    }
                    OutGridView.RefreshRow(RowHandle);
                }
            }
            else if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {//清空内容
                int RowHandle = OutGridView.GetSelectedRows()[0];
                DataRow data = OutData.Rows[RowHandle];
                data["ColumnValue"] = "";
                data["CaptionColumn"] = "";
                data["column"] = "";
                data["languageTexts"] = "";
                OutGridView.RefreshRow(RowHandle);
            }
        }

        private string removeBracket(string arg)
        {
            StringBuilder text = new StringBuilder();
            int index = arg.IndexOf("(");
            int timer = 20;
            while (index > 0 && timer > 0)
            {
                int begin = index;
                int end = -1;
                int Number = 0;
                text.Clear();
                for (int i = begin + 1; i < arg.Length; i++)
                {
                    char str = arg[i];
                    if (str == '(')
                    {
                        Number++;
                    }
                    else if (str == ')')
                    {
                        if (Number > 0)
                        {
                            Number--;
                        }
                        else
                        {
                            end = i;
                            break;
                        }
                    }
                }
                if (end != -1)
                {
                    text.Append(arg.Substring(0, begin)).Append(" ");
                    text.Append(arg.Substring(end + 1));
                }
                else
                {
                    text.Append(arg.Substring(0, begin));
                    text.Append(arg.Substring(begin + 1));
                }
                timer--;
                arg = text.ToString();
                index = arg.IndexOf("(");
            }

            return arg;
        }
    }
}